package com.lzx.adx.report.support.strategy.media;

import cn.hutool.core.util.IdUtil;
import cn.hutool.http.HttpUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.google.common.collect.Lists;
import com.lzs.adx.commmon.utils.Result;
import com.lzx.adx.report.annnotions.MediaType;
import com.lzx.adx.report.constant.MediaChannelConstant;
import com.lzx.adx.report.dto.AccountDTO;
import com.lzx.adx.report.dto.ReportDTO;
import com.lzx.adx.report.dto.ViVoData;
import com.lzx.adx.report.model.vivo.ViVoRequest;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Component;

import java.util.HashMap;
import java.util.Map;

@Component
@Slf4j
@MediaType(MediaChannelConstant.VIVO)
public class ViVoCallBackStrategy extends AbstractCallback{
    @Override
    public ResponseEntity callback(ReportDTO reportDTO, AccountDTO accountDTO, String callType, String ts) {
        boolean base = base(reportDTO, accountDTO, callType, ts);
        if(!base){
            return ResponseEntity.status(HttpStatus.BAD_REQUEST).build();
        }
        String sspExtend = accountDTO.getSspExtend();
        JSONObject jsonObject = JSONObject.parseObject(sspExtend);
        String eventType = jsonObject.getString(callType);


        ViVoData viVoData = new ViVoData();
        viVoData.setCvTime(ts);
        viVoData.setCvType(eventType);
        viVoData.setRequestId(reportDTO.getRequestId());
        viVoData.setCreativeId(reportDTO.getContentId());
        if ("PAY".equals(eventType)){
            ViVoData.ExtParam extParam=new ViVoData.ExtParam();
            viVoData.setExtParam(extParam);
        }
        Map<String, Object> paramsMap = new HashMap<>();
        paramsMap.put("srcType","WEB");
        paramsMap.put("pageUrl",jsonObject.getString("pageUrl"));
        paramsMap.put("srcId",jsonObject.getString("srcId"));
        paramsMap.put("dataList", Lists.newArrayList(viVoData));
        String resultPams = JSON.toJSONString(paramsMap);
        String url = accountDTO.getSspApiUrl() + "?access_token=" + accountDTO.getSspKey() + "&timestamp=" + ts + "&nonce=" + IdUtil.fastSimpleUUID() + "&advertiser_id=" + reportDTO.getAid();
        log.info("账号{}，请求id{}给vivo请求地址为地址为：{}，请求参数为{}", reportDTO.getDspId(), reportDTO.getBizRequestId(), url, resultPams);
        String post = HttpUtil.post(url, resultPams);
        log.info("账号{}，请求id{}给vivo请求转换响应的结果为：{}", reportDTO.getDspId(), reportDTO.getBizRequestId(), post);
        return ResponseEntity.ok(new Result());
    }
}
